package com.pj.wisdomlogistics.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.pj.wisdomlogistics.MyApplication;
import com.pj.wisdomlogistics.R;
import com.pj.wisdomlogistics.cons.Cons;
import com.pj.wisdomlogistics.entity.CarDetailInfo;
import com.pj.wisdomlogistics.mvp.contract.CarDetailContract;
import com.pj.wisdomlogistics.mvp.frame.MvpActivity;
import com.pj.wisdomlogistics.mvp.frame.base.BaseView;
import com.pj.wisdomlogistics.mvp.presenter.CarDetailPresenter;
import com.pj.wisdomlogistics.other.EventCenter;
import com.pj.wisdomlogistics.ui.view.CustomAlertDialog;
import com.pj.wisdomlogistics.utils.ActivityManagerUtil;
import com.pj.wisdomlogistics.utils.ButtonGrayUtils;
import com.pj.wisdomlogistics.utils.CustomToast;
import com.pj.wisdomlogistics.utils.PdfDownload;
import com.pj.wisdomlogistics.utils.ShowPop;
import com.pj.wisdomlogistics.utils.ToSign;
import com.willy.ratingbar.ScaleRatingBar;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

public class CarDetailActivity extends MvpActivity<CarDetailPresenter> implements CarDetailContract.View,  ShowPop.listener, BaseActivity.RequestPermission {

    @BindView(R.id.tv_apply_detail_dept)
    TextView mTvApplyDetailDept;
    @BindView(R.id.tv_apply_detail_contacts)
    TextView mTvApplyDetailContacts;
    @BindView(R.id.tv_apply_detail_call)
    TextView mTvApplyDetailCall;
    @BindView(R.id.tv_apply_detail_phone)
    TextView mTvApplyDetailPhone;
    @BindView(R.id.tv_apply_detail_apply_date)
    TextView mTvApplyDetailApplyDate;
    @BindView(R.id.rel_basic_info)
    RelativeLayout mRelBasicInfo;
    @BindView(R.id.tv_apply_detail_content)
    TextView mTvApplyDetailContent;
    @BindView(R.id.tv_apply_detail_reason)
    TextView mTvApplyDetailReason;
    @BindView(R.id.tv_apply_detail_meeting_destination)
    TextView mTvApplyDetailMeetingDestination;
    @BindView(R.id.tv_apply_detail_detail_reason)
    TextView mTvApplyDetailDetailReason;
    @BindView(R.id.apply_detail_car_time)
    TextView mApplyDetailCarTime;
    @BindView(R.id.tv_apply_detail_contact)
    TextView mTvApplyDetailContact;
    @BindView(R.id.tv_apply_detail_mobile)
    TextView mTvApplyDetailMobile;
    @BindView(R.id.iv_apply_leader_sign)
    ImageView mIvApplyLeaderSign;
    @BindView(R.id.ll_apply_leader_sign)
    LinearLayout mLlApplyLeaderSign;
    @BindView(R.id.tv_turn_sign)
    TextView mTvTurnSign;
    @BindView(R.id.iv_apply_dept_stamp)
    ImageView mIvApplyDeptStamp;
    @BindView(R.id.ll_apply_dept_stamp)
    LinearLayout mLlApplyDeptStamp;
    @BindView(R.id.tv_apply_detail_manager_leader)
    TextView mTvApplyDetailManagerLeader;
    @BindView(R.id.tv_turn_check)
    TextView mTvTurnCheck;
    @BindView(R.id.tv_turn_portion)
    TextView mTvTurnPortion;
    @BindView(R.id.tv_apply_detail_manager_charge_leader)
    TextView mTvApplyDetailManagerChargeLeader;
    @BindView(R.id.tv_apply_detail_manager_charger_phone)
    TextView mTvApplyDetailManagerChargerPhone;
    @BindView(R.id.tv_apply_detail_car_info)
    TextView mTvApplyDetailCarInfo;
    @BindView(R.id.tv_apply_detail_driver_info)
    TextView mTvApplyDetailDriverInfo;
    @BindView(R.id.bt_on)
    Button mBtOn;
    @BindView(R.id.bt_off)
    Button mBtOff;
    @BindView(R.id.ratingBar)
    ScaleRatingBar mSRatingBar;
    @BindView(R.id.ll_pj)
    LinearLayout mLayoutPj;
    @BindView(R.id.tv_access)
    TextView mTvAccess;
    @BindView(R.id.tv_leader_name)
    TextView mTvLeaderName;
    @BindView(R.id.tv_stamp_time)
    TextView mTvStampTime;
    @BindView(R.id.tv_apply_detail_detail_count)
    TextView mTvCount;
    @BindView(R.id.ll_car_finish)
    LinearLayout mLayoutFinsh;
    @BindView(R.id.et_mileage_before)
    EditText mEtMileageBefore;
    @BindView(R.id.et_mileage_after)
    EditText mEtMileageAfter;
    @BindView(R.id.ll_mile)
    LinearLayout mLayoutMile;
    @BindView(R.id.tv_mile)
    TextView mTvMile;
    @BindView(R.id.tv_apply_detail_car_place)
    TextView mTvPlace;

    private int id;
    private int carTransactId;
    private String currentStampUrl;

    private int carApplyId;
    private String carId;

    private boolean isSign = false;
    private boolean isCheck = false;

    private String[] permission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private Bitmap mBitmap;

    @BindView(R.id.tv_undo)
    TextView mTvUndo;
    private CustomAlertDialog mCustomAlertDialog;
    private int carTransactHistroyId;

    @Override
    public void onError(String errorMsg) {
        dismissProgressDialog();
        Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSuccess(final CarDetailInfo mInfo) {
        dismissProgressDialog();

        carApplyId = mInfo.getCarApplyID();
        carId = mInfo.getCarID();
        currentStampUrl = mInfo.getCheck2Sign();

        RequestOptions options = new RequestOptions()
                .centerCrop()
                .priority(Priority.HIGH);

        //已撤销的单子，或非首页、我的申请进来的单子，不展示撤销按钮
        if (mInfo.getCancel() == 1 || carApplyId == -1 || !mInfo.getUserID().equals(MyApplication.userID)) {
            mTvUndo.setVisibility(View.GONE);
        }else{
            mTvUndo.setVisibility(View.VISIBLE);
        }
        

        //已签字
        if (mInfo.getCheck1() == 1) {
            mLlApplyLeaderSign.setVisibility(View.VISIBLE);
            Glide.with(this).load(mInfo.getCheck1Sign()).apply(options).into(mIvApplyLeaderSign);
        }

        if (mInfo.getCheck1() == 2) {
            mTvTurnSign.setVisibility(View.VISIBLE);
            mTvTurnSign.setText(String.format(getResources().getString(R.string.apply_detail_turn_down,
                    mInfo.getCheck1Comments() + mInfo.getSignBackTime())));
        }

        //已盖章
        if (mInfo.getCheck2() == 1) {
            mLlApplyDeptStamp.setVisibility(View.VISIBLE);
            mTvStampTime.setText(mInfo.getSealTime());

            //申请单盖章之后，后续步骤上的人员皆可看到单子，单从下下步开始的人，无法处理
            outer:
            for (int i = 0; i < MyApplication.user.getRoleId().size(); i++) {
                switch (MyApplication.user.getRoleId().get(i)) {
                    case Cons.RoleId.PORITION_CAR:
                        ButtonGrayUtils.buttonGray(mBtOn, mBtOff, "分配", "驳回", mInfo.getState() <= 2);
                        break outer;
                }
            }
        }

        //已审核
        if (mInfo.getCheck3() == 1) {
            mTvApplyDetailManagerLeader.setVisibility(View.VISIBLE);
            mTvApplyDetailManagerLeader.setText("管理中心分管主任：已同意" + "    " + mInfo.getReviewName() + "    " + mInfo.getRevieweTime());
        }

        if (mInfo.getCheck3() == 2) {
            mTvTurnCheck.setVisibility(View.VISIBLE);
            mTvTurnCheck.setText(String.format(getResources().getString(R.string.apply_detail_turn_down,
                    mInfo.getCheck3Comments() + "    " + mInfo.getRevieweBackTime())));
        }

        //已分配
        if (mInfo.getCheck4() == 1) {
            mTvApplyDetailManagerChargeLeader.setVisibility(View.VISIBLE);
            mTvApplyDetailManagerChargeLeader.setText(
                    "管理中心车队长：已分配    " + mInfo.getLeaderName());
            mTvApplyDetailManagerChargerPhone.setVisibility(View.VISIBLE);
            mTvApplyDetailManagerChargerPhone.setText("    " + mInfo.getAllotTime());
            mTvApplyDetailCarInfo.setVisibility(View.VISIBLE);
            String carInfo = "";

            carInfo += mInfo.getCarModel() + "  "
                    + mInfo.getCarNum();

            mTvApplyDetailCarInfo.setText(String.format(getResources().getString(R.string.apply_detail_car_info, carInfo)));

            mTvApplyDetailDriverInfo.setVisibility(View.VISIBLE);
            String driverInfo = "";

            driverInfo += mInfo.getDriver() + "  "
                    + mInfo.getDriverTel();

            mTvApplyDetailDriverInfo.setText(String.format(getResources().getString(R.string.apply_detail_driver_info, driverInfo)));

        }
        if (mInfo.getCheck4() == 2) {
            mTvTurnPortion.setVisibility(View.VISIBLE);
            mTvTurnPortion.setText(String.format(getResources().getString(R.string.apply_detail_turn_down,
                    mInfo.getCheck4Comments() + "    " + mInfo.getAllotBackTime())));
        }

        if(mInfo.getCheck5() == 1){
            mLayoutMile.setVisibility(View.VISIBLE);
            mTvMile.setText(String.format(getResources().getString(R.string.apply_detail_car_mile, mInfo.getBeforeMile() + "公里", mInfo.getAfterMile() + "公里")));
            mLayoutFinsh.setVisibility(View.GONE);
        }

        if(mInfo.getState() == 4 && carTransactId != -1){
            for (int i = 0; i < MyApplication.user.getRoleId().size(); i++) {
                switch (MyApplication.user.getRoleId().get(i)) {
                    case Cons.RoleId.PORITION_CAR:
                        mLayoutFinsh.setVisibility(View.VISIBLE);
                        break;
                }
            }
        }

        //待评价
        if (mInfo.getState() == 5 && carTransactId == -1) {
            mBtOn.setVisibility(View.VISIBLE);
            mBtOn.setText("评价");
            mBtOn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ShowPop.showTurnDown(CarDetailActivity.this, 101, mBtOff);
                }
            });
        }



        //已评价
        if (mInfo.getState() == 6) {
            mSRatingBar.setVisibility(View.VISIBLE);
            mSRatingBar.setRating(mInfo.getLevels());
            mLayoutPj.setVisibility(View.VISIBLE);
            mTvAccess.setText(TextUtils.isEmpty(mInfo.getAssess()) ? "无" : mInfo.getAssess());
            mSRatingBar.setTouchable(false);
        }

        mTvApplyDetailDept.setText(String.format(getResources().getString(R.string.apply_detail_dept, mInfo.getApplyDept())));
        mTvApplyDetailCall.setText(String.format(getResources().getString(R.string.apply_detail_call, mInfo.getOfficeTel())));
        mTvApplyDetailContacts.setText(String.format(getResources().getString(R.string.apply_detail_contacts, mInfo.getLinkman())));
        mTvApplyDetailPhone.setText(String.format(getResources().getString(R.string.apply_detail_phone, mInfo.getUserTel())));
        mTvApplyDetailApplyDate.setText(String.format(getResources().getString(R.string.apply_detail_apply_date, mInfo.getApplyDate())));
        String detailReason = "";
        switch (mInfo.getApplyReason()) {
            case 1:
                detailReason = "应急";
                break;
            case 0:
                detailReason = "调研";
                break;
            case 2:
                detailReason = "接待";
                break;
        }
        mTvApplyDetailReason.setText(String.format(getResources().getString(R.string.apply_detail_cause, detailReason)));
        mTvApplyDetailMeetingDestination.setText(String.format(getResources().getString(R.string.apply_detail_destination, mInfo.getGoalPlace())));
        mTvApplyDetailDetailReason.setText(String.format(getResources().getString(R.string.apply_detail_reason, mInfo.getDetailReason())));
        mTvCount.setText("用车人数：" + mInfo.getPeopleCount() + "人");
        mApplyDetailCarTime.setText(String.format(getResources().getString(R.string.apply_detail_car_time, mInfo.getUsingTime())));
        mTvApplyDetailContact.setText(String.format(getResources().getString(R.string.apply_detail_contact, mInfo.getLinkman())));
        mTvApplyDetailMobile.setText(String.format(getResources().getString(R.string.apply_detail_contact_tel, mInfo.getLinkmanTel())));
        mTvLeaderName.setText(mInfo.getSignName() + "    " + mInfo.getSignTime());
        if(mInfo.getPlace() == null){
            mTvPlace.setText("用车地点：无");
        }else{
            mTvPlace.setText("用车地点：" + (mInfo.getPlace().equals("1") ? "政府大楼" : mInfo.getPlace().equals("2") ? "双和园" : "无"));
        }


        ////////////////////////以上为基本信息，以下为我的待办//////////////////////////////////

        if (mInfo.getState() == 0 && carTransactId != -1 && !MyApplication.isGzh) {
            for (int i = 0; i < MyApplication.user.getRoleId().size(); i++) {
                if(MyApplication.user.getRoleId().get(i).equals(Cons.RoleId.SIGN)){
                    mBtOn.setVisibility(View.VISIBLE);
                    mBtOff.setVisibility(View.VISIBLE);

                    mBtOn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //签字
                            ToSign.sign(CarDetailActivity.this);
                        }
                    });

                    mBtOff.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //驳回
                            ShowPop.showTurnDown(CarDetailActivity.this, 8, mBtOff);
                        }
                    });
                }
            }
        }

        if (mInfo.getState() == 2 && carTransactId != -1 && !MyApplication.isGzh) {
            for (int i = 0; i < MyApplication.user.getRoleId().size(); i++) {
                if (MyApplication.user.getRoleId().get(i).equals(Cons.RoleId.CHECK_CAR)) {
                    mBtOn.setVisibility(View.VISIBLE);
                    mBtOff.setVisibility(View.VISIBLE);

                    mBtOn.setText("同意");
                    mBtOff.setText("驳回");


                    mBtOn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //审核
                            mPresenter.carApplyComment(
                                    MyApplication.userID,
                                    id != -1 ? id : carTransactId,
                                    "",
                                    3
                            );
                            isCheck = true;
                            showProgressDialog();
                        }
                    });

                    mBtOff.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //驳回
                            ShowPop.showTurnDown(CarDetailActivity.this, 9, mBtOff);
                        }
                    });

                }
            }
        }

        if (mInfo.getState() == 3 && carTransactId != -1 && !MyApplication.isGzh) {
            for (int i = 0; i < MyApplication.user.getRoleId().size(); i++) {
                if (MyApplication.user.getRoleId().get(i).equals(Cons.RoleId.PORITION_CAR)) {
                    mBtOn.setVisibility(View.VISIBLE);
                    mBtOff.setVisibility(View.VISIBLE);

                    mBtOn.setText("分配");

                    mBtOn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //分配
                            Intent mIntent = new Intent(CarDetailActivity.this, CarPoritionActivity.class);
                            mIntent.putExtra(Cons.CarInfo.CAR_PORITION, mInfo.getCarApplyID());
                            startActivity(mIntent);
                        }
                    });

                    mBtOff.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //驳回
                            ShowPop.showTurnDown(CarDetailActivity.this, 10, mBtOff);
                        }
                    });
                }
            }
        }

        if (mInfo.getState() == 4 && (carTransactId != -1 || carTransactHistroyId != -1)&& !MyApplication.isGzh) {
            for (int i = 0; i < MyApplication.user.getRoleId().size(); i++) {
                if (MyApplication.user.getRoleId().get(i).equals(Cons.RoleId.PORITION_CAR)) {
                    mBtOn.setVisibility(View.VISIBLE);
                    if(carTransactHistroyId == -1){
                        mBtOn.setText("完成");
                        mBtOn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //完成
                                if(TextUtils.isEmpty(mEtMileageBefore.getText().toString().trim())
                                        || TextUtils.isEmpty(mEtMileageAfter.getText().toString().trim())){
                                    CustomToast.showToast(CarDetailActivity.this , "请将资料填写完整" , 1000);
                                    return;
                                }
                                mPresenter.carApplyFinish(
                                        MyApplication.userID,
                                        carApplyId ,
                                        mEtMileageBefore.getText().toString().trim() ,
                                        mEtMileageAfter.getText().toString().trim());
                                showProgressDialog();
                            }
                        });
                    }else{
                        mBtOn.setText("重新分配");
                        mBtOn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //重新分配
                                Intent mIntent = new Intent(CarDetailActivity.this, CarPoritionActivity.class);
                                mIntent.putExtra(Cons.CarInfo.CAR_PORITION, mInfo.getCarApplyID());
                                startActivity(mIntent);
                            }
                        });
                    }

                }
            }
        }

    }

    @Override
    public void onSignSuccess() {
        successToast(isSign ? "签字成功" : "驳回成功");
    }

    @Override
    public void onCheckSuccess() {
        successToast(isCheck ? "审核成功" : "驳回成功");
    }

    @Override
    public void onSendSuccess() {
        successToast("驳回成功");
    }

    @Override
    public void onPjSuccess() {
        dismissProgressDialog();
        CustomToast.showToast(this, "评价成功", 1000);
        EventBus.getDefault().post(new EventCenter<String>(Cons.Other.MY_APPLY));
        mPresenter.findCarApplyDetail(id != -1 ? id : carTransactId);
        mBtOn.setVisibility(View.GONE);
        mBtOff.setVisibility(View.GONE);
    }

    @Override
    public void onFinishSuccess() {
        successToast("提交成功");
    }

    @Override
    public void onUndoSuccess() {
        dismissProgressDialog();
        CustomToast.showToast(this, "撤销成功", 1000);
        EventBus.getDefault().post(new EventCenter<>(Cons.Other.MY_APPLY));
        ActivityManagerUtil.create().finishActivity();
    }

    public void successToast(String toast) {
        dismissProgressDialog();
        CustomToast.showToast(this, toast, 1000);
        EventBus.getDefault().post(new EventCenter<String>(Cons.Other.MY_TRANSACT));
        mPresenter.findCarApplyDetail(id != -1 ? id : carTransactId);
        mBtOn.setVisibility(View.GONE);
        mBtOff.setVisibility(View.GONE);
    }

    @Override
    protected BaseView getBaseView() {
        return this;
    }

    @Override
    public void initView() {
        ultimateBar.setColorBar(ContextCompat.getColor(this, R.color.text_blue));

        id = getIntent().getIntExtra(Cons.CarInfo.CAR_ID, -1);
        carTransactId = getIntent().getIntExtra(Cons.CarInfo.CAR_TRANSACT_ID, -1);
        carTransactHistroyId = getIntent().getIntExtra(Cons.CarInfo.CAR_TRANSACT_HISTROY_ID , -1);

        mPresenter.findCarApplyDetail(id != -1 ? id : carTransactId == -1 ? carTransactHistroyId : carTransactId);
        showProgressDialog();

        setRequestPermissionListener(this);

        ShowPop.setListner(this);
    }

    @Override
    public void initData() {

    }

    @Override
    public int getContentView() {
        return R.layout.activity_car_detail;
    }

    @Override
    public boolean isApplyEventBus() {
        return true;
    }

    @Override
    public boolean isApplyButterKnife() {
        return true;
    }

    @Override
    public void onEventCome(EventCenter eventCenter) {
        if (eventCenter.getEventCode() == Cons.CarInfo.SURE_OK) {
            //分配成功
            mBtOn.setVisibility(View.GONE);
            mBtOff.setVisibility(View.GONE);
            mPresenter.findCarApplyDetail(id != -1 ? id : carTransactId);
            showProgressDialog();
            EventBus.getDefault().post(new EventCenter<>(Cons.CarInfo.CAR_TRANSACT_OK));
        }
    }

    @OnClick({R.id.iv_back, R.id.iv_apply_dept_stamp , R.id.tv_undo})
    public void onViewClicked(View mView) {
        switch (mView.getId()) {
            case R.id.iv_back:
                ActivityManagerUtil.create().finishActivity();
                break;
            case R.id.iv_apply_dept_stamp:
                if (!checkPermissions(permission)) {
                    requestSystemPermissions(permission, 101);
                } else {
                    PdfDownload.pdfDownload(this, currentStampUrl);
                }
                break;
            case R.id.tv_undo:
                mCustomAlertDialog = new CustomAlertDialog.Builder(this)
                        .setMessage("确认撤销该申请单吗？")
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mPresenter.cancelCar(carApplyId != -1 ? carApplyId : carTransactId);
                                showProgressDialog();
                                mCustomAlertDialog.dismiss();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mCustomAlertDialog.dismiss();
                            }
                        }).create();
                mCustomAlertDialog.show();
                break;
        }

    }

    @Override
    public void showTurnDown(int state, String text, int rating) {
        if (state == 8) {
            mPresenter.carApplySign(
                    id != -1 ? id : carTransactId,
                    MyApplication.userID,
                    null,
                    state,
                    text);
            isSign = false;
        } else if (state == 9) {
            mPresenter.carApplyComment(
                    MyApplication.userID,
                    id != -1 ? id : carTransactId,
                    text,
                    state
            );
            isCheck = false;
        } else if (state == 10) {
            mPresenter.carApplyAllot(
                    MyApplication.userID,
                    carApplyId + "",
                    state + "",
                    "",
                    "",
                    "",
                    "",
                    "",
                    carId,
                    text
            );
        } else if (state == 101) {
            mPresenter.carApplyAssess(
                    text,
                    carApplyId + "",
                    rating
            );
        }
        showProgressDialog();
    }

    @Override
    public void onRequestResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 101) {
            if (!checkPermissions(permission)) {
                CustomToast.showToast(this, "您拒绝了相关权限的请求", 1000);
            } else {
                PdfDownload.pdfDownload(this, currentStampUrl);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == 1){
            String path = data.getStringExtra("path");

            if(TextUtils.isEmpty(path)) return;
            File mFile = new File(path);
            toSign(mFile);
        }
    }

    private void toSign(File mFile){
        //上传签名
        mPresenter.carApplySign(
                id != -1 ? id : carTransactId,
                MyApplication.userID,
                mFile,
                1,
                "");

        isSign = true;

        showProgressDialog();
    }
}
